package com.wgj.android.accesslibility.job;
import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Parcelable;
import android.os.PowerManager;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.wgj.android.accesslibility.AccessibilityHelper;
import com.wgj.android.accesslibility.IStatusBarNotification;
import com.wgj.android.accesslibility.config.WXIDManage;
import com.wgj.android.accesslibility.config.WXPageUIManage;
import com.wgj.android.accesslibility.config.WXQiangHongBaoConfig;

import com.wgj.android.accesslibility.service.WGJAccessServier;
import com.wgj.android.base.WGJApplication;
import com.wgj.android.entity.BonusHistory;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.utils.NotifyHelper;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.KEYGUARD_SERVICE;
/**
 * Created by Administrator on 2017/11/17.
 */
public class QHBAccessbilityJob implements  AccessbilityJob {
     private  static int weixinversion=0;
     private  static  int weignum=0;
     private static  final  String TAG="QHBAccessbilityJob";
     private boolean isReceivingHongbao;
     private AccessibilityService service;
     private boolean isRunning;      //是否正处于打开红包流程中
     private boolean isBackward;     //是否刚从开完红包页面返回到聊天界面
     private boolean isOpenQHB=false;//是否开启了红包

    @Override
    public String getTargetPackageName() {
        return WECHAT_PACKAGENAME;
    }

    @Override
    public void onCreateJob(AccessibilityService service) {
        WXQiangHongBaoConfig.setIsEnableWechat(true);
        this.service=service;
        Log.i(TAG,"创建红包任务");
    }

    @Override
    public void onReceiveJob(final AccessibilityEvent event){
        try {
            Log.i(TAG,"ClassName:"+event.getClassName().toString());
            final  int eventType=event.getEventType();
            switch (eventType){
                 case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:{//收到通知道

                    Parcelable data = event.getParcelableData();
                    if(data == null || !(data instanceof Notification)) {
                        return;
                    }
                    List<CharSequence> texts = event.getText();
                    String text = String.valueOf(texts.get(0));
                     Log.e(TAG,"TYPE_NOTIFICATION_STATE_CHANGED:" +text);
                    if(text.contains(WXPageUIManage.HONGBAO_TEXT_KEY)) {
                        notificationEvent((Notification) data);
                    }
                 }
                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                    String   currentActivity = String.valueOf(event.getClassName());
                    if(WXPageUIManage.isQHBUI(currentActivity)){//是否已弹出了红包窗口

                        //当前在红包待开页面，去拆红包
                        new Handler().postDelayed(new Runnable() {
                            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                            @Override
                            public void run() {
                                getLuckyMoney(event);
                            }
                        }, 100);
                        return;
                     }
                     if(WXPageUIManage.isLuckyMoneyDetailUI(currentActivity)){//是否已经拆完了红包到了红包领取记录了
                         isRunning = false;
                         //拆完红包后看详细纪录的界面

                         if(isOpenQHB){//点击了拆红包才会添加到记录中
                             addHongBaoHistory();//添加红包记录
                         }
                         return;
                     }
                     if(WXPageUIManage.isMainUI(currentActivity)){
                         //在聊天界面,去点中红包
                         new Handler().postDelayed(new Runnable() {
                             @Override
                             public void run() {
                                 openLuckyEnvelope();
                             }
                         }, 100);
                     }

                    break;

            }
        }catch (Exception e){
            Log.e(TAG,"初理红包消息异常!"+e.getMessage());
        }

    }

    //开红包
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void getLuckyMoney(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo nodeInfo =service.getRootInActiveWindow();  //获得整个窗口对象
            if (nodeInfo == null) { //部份手机开始获取不到窗口则退回到桌面在次打开微信
                AccessibilityHelper.performHome(service);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startActivityForPackage(getContext(),WECHAT_PACKAGENAME);
                    }
                },300);
                return;
            }
            AccessibilityNodeInfo qhbBut= AccessibilityHelper.findNodeInfosById(nodeInfo,WXIDManage.getHongBaoId(weixinversion));
            if(qhbBut!=null){
                AccessibilityHelper.performClick(qhbBut);
                isOpenQHB=true;
            }else {
                AccessibilityHelper.performBack(service);
                if(WXQiangHongBaoConfig.getWechatAfterOpenHongBao()) { //返回主界面，以便收到下一次的红包通知
                    AccessibilityHelper.performHome(service);
                }
            }
        }catch (Exception e){
                 Log.e(TAG,"打开红包出错啦");
        }
    }


    //点击进入红包待开启界面
    private void openLuckyEnvelope() {
        try {
            AccessibilityNodeInfo nodeInfo = service.getRootInActiveWindow();
            if (nodeInfo == null) {
                return;
            }
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("领取红包");
            if (list.isEmpty()) {
                openChatPage(nodeInfo);
            } else {
                //选择聊天记录中最新的红包
                for (int i = list.size() - 1; i >= 0; i--) {
                    AccessibilityNodeInfo parent = list.get(i).getParent();
                    Log.d(TAG, "-->领取红包:" + parent);
                    if (parent != null) {
                        parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        break;
                    }
                }
            }
        }catch (Exception e){
            Log.e(TAG,"打开红包出错啦");
        }

    }

    //打开聊天内页
    private void openChatPage(AccessibilityNodeInfo nodeInfo) {
        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("[微信红包]恭喜发财，大吉大利");
        if (!list.isEmpty()) {
            for (int j = 0; j < list.size(); j++) {
                AccessibilityNodeInfo node = list.get(j);
                while (node != null && !node.isClickable()) {
                    node = node.getParent();
                }
                if (node != null) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        }
    }

    @Override
    public void onStopJob() {
        WXQiangHongBaoConfig.setIsEnableWechat(false);
    }

    /**
     * 收到通知道栏的事件
     * @param sbn
     */
    @Override
    public void onNotificationPosted(IStatusBarNotification sbn) {
        try {
            notificationEvent(sbn.getNotification());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void setWeiXingVersion(int version) {
        weixinversion=version;
    }

    /** 通知栏事件*/
    private void notificationEvent( Notification nf) throws Exception{
        try {
            newHongBaoNotification(nf);
        }catch (Exception e){
             Log.e(TAG,"处理通知栏事件异常!"+e.getMessage());
             throw  new Exception("处理通知栏事件异常!"+e.getMessage());
        }

    }

    /** 打开通知栏消息*/
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void newHongBaoNotification(Notification notification)throws  Exception {
        try {
            isReceivingHongbao = true;
            final PendingIntent pendingIntent = notification.contentIntent;
            boolean lock = NotifyHelper.isLockScreen(getContext());
            if(lock && !checkPasswordToUnLock()) {
                wakeUpAndUnlock(getContext());
                NotifyHelper.send(pendingIntent);
                NotifyHelper.playEffect(getContext());
            }else {
                NotifyHelper.send(pendingIntent);
                NotifyHelper.playEffect(getContext());
            }
        }catch (Exception e){
            Log.e(TAG,"打开通知栏消息失败!"+e.getMessage());
            throw  new Exception(e.getMessage());
        }


       // NotifyHelper.showNotify(getContext(), String.valueOf(notification.tickerText), pendingIntent);

        //NotifyHelper.showNotify(getContext(), String.valueOf(notification.tickerText), pendingIntent);


    }

    @Override
    public boolean isEnable() {
         return WXQiangHongBaoConfig.isEnableWechat();
    }

    private Context getContext(){
        return  service.getApplicationContext();
    }

    @SuppressLint("LongLogTag")
    private  void addHongBaoHistory()throws Exception{
        try {
            isOpenQHB=false;
            AccessibilityNodeInfo nodeInfo = service.getRootInActiveWindow();
            if(nodeInfo == null) {
                Log.w(TAG, "rootWindow为空");
                return;
            }

            final String friends=AccessibilityHelper.findNodeInfosById(nodeInfo,WXIDManage.getHongBaoFriendId(weixinversion)).getText().toString();
            final double money=Double.valueOf(AccessibilityHelper.findNodeInfosById(nodeInfo,WXIDManage.getHongBaoMoneyId(weixinversion)).getText().toString());

            Map<String,Object> params=new HashMap<>();
            params.put("mId", CacheUtils.getMember().getM_id());
            params.put("amount", money);
            params.put("name", friends);
            XHttp.obtain().post(WGJAPI.BASEURL.concat("/hb/save"), params, new HttpCallBack<String>() {
                @Override
                public void onSuccess(String s) {

                }

                @Override
                public void onFailed(int i, String s, boolean b) {

                }
            });
            AccessibilityHelper.performBack(service);
            if(WXQiangHongBaoConfig.getWechatAfterOpenHongBao()){
                AccessibilityHelper.performHome(service);
            }


        }catch (Exception e){
            Log.e(TAG,"添加红包历史失败!"+e.getMessage());
            throw new Exception(e.getMessage());
        }

    }

    @SuppressLint("MissingPermission")
    public  void wakeUpAndUnlock(Context context)throws Exception {
        try {
            //获取电源管理器对象
            PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
            //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
            //点亮屏幕
            wl.acquire(10000);
            //释放
            wl.release();
            // 屏幕解锁
            KeyguardManager keyguardManager = (KeyguardManager) getContext()
                    .getSystemService(KEYGUARD_SERVICE);
            KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
            // 屏幕锁定
            keyguardLock.reenableKeyguard();
            keyguardLock.disableKeyguard(); // 解锁
        }catch (Exception e){
            Log.e(TAG,"唤醒屏幕失败!"+e.getMessage());
            throw new Exception(e.getMessage());
        }



    }

    private boolean checkPasswordToUnLock(){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            KeyguardManager keyguardManager = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
            return keyguardManager.isKeyguardSecure();
        }else{
            return isSecured();
        }
    }

    private boolean isSecured(){
        boolean isSecured = false;
        String classPath = "com.android.internal.widget.LockPatternUtils";
        try{
            Class<?> lockPatternClass = Class.forName(classPath);
            Object lockPatternObject = lockPatternClass.getConstructor(Context.class).newInstance(getContext());
            Method method = lockPatternClass.getMethod("isSecure");
            isSecured = (boolean) method.invoke(lockPatternObject);
        }catch (Exception e){
            isSecured = false;
        }
        return isSecured;
    }

    public static void startActivityForPackage(Context context, String packName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packName);
        context.startActivity(intent);
    }
}
